package com.zyb.system.fastdfs.controller;

import com.zyb.utils.AjaxResult;
import com.zyb.utils.FastdfsUtil;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/fast")
@Api(value = "文件上传的API",description="文件上传下载功能")
public class FastDFSController {
    //上传
    @PostMapping
    public AjaxResult upload(@RequestPart(required = true,value = "file") MultipartFile file){
        try {
            byte[] bytes = file.getBytes();
            String filename = file.getOriginalFilename();
            String suffix = filename.substring(filename.lastIndexOf(".") + 1);
            String uploadPath = FastdfsUtil.upload(bytes,suffix);
            return AjaxResult.success().setData(uploadPath);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error().setMsg("网络异常,请联系管理员");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error().setMsg("网络异常,请稍后重试");
        }
    }

    //删除
    @DeleteMapping
    public AjaxResult delete(@RequestParam(required = true,value = "path") String path){
        try {
            String filePath = path.substring(1);
            String group = filePath.substring(0, filePath.indexOf("/"));
            String lastPath = filePath.substring(filePath.indexOf("/") + 1);
            FastdfsUtil.delete(group,lastPath);
            return AjaxResult.success().setMsg("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error().setMsg("网络异常,请联系管理员");
        }
    }
}
